# -*- coding:utf-8 -*-

from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django import forms
from RegModel.models import Reg

#表单
class UserForm(forms.Form):
	"""docstring for UserForm"""
	name = forms.CharField(label='用户名',max_length = 100)
	password = forms.CharField(label = '密码',widget = forms.PasswordInput())

#注册		
def regist(req):
	if req.method =='POST':
		uf = UserForm(req.POST)
		if uf.is_valid():
			#获得表单数据
			name = uf.cleaned_data['name']
			password = uf.cleaned_data['password']
			#添加到数据库
			Reg.objects.create(name = name,password = password)
			return HttpResponse('Regist success!!')
	else:
		uf = UserForm
	return render_to_response('regist.html',{'uf':uf},
		context_instance = RequestContext(req))
#登入
def login(req):
	if req.method =='POST':
		uf = UserForm(req.POST)
		if uf.is_valid():
			#获取表单用户密码
			name = uf.cleaned_data['name']
			password = uf.cleaned_data['password']
		 	#获取的表单数据与数据库进行比较
		 	user = Reg.objects.filter(name = name, password = password)
		 	if user:
		 		#比较成功，跳转index
		 		response = HttpResponseRedirect('/Reg/index/')
		 		#将name 写入cookie，失效时间为3600
		 		response.set_cookie('name',name,3600)
		 		return response
		 	else:
		 		#比较失败，还在login
		 		return HttpResponseRedirect('/Reg/login')
	else:
		uf = UserForm()
	return render_to_response('login.html',{'uf':uf},context_instance =RequestContext(req))
#登入成功
def index(req):
	name = req.COOKIES.get('name','')
	return render_to_response('index.html',{'name':name})
#退出
def logout(req):
	response = HttpResponse('logout!!')
	#清理cookie里保存的name
	response.delete_cookie('name')
	return response	